<template>
  <div class="main">
    <div class="container">
      <div class="sidebar">
        <div class="u4-logo-c">
          <div class="u4-logo"></div>
        </div>
        <div class="service-list">
          <h3>{{$t("首页")}}</h3>
          <ul class="notification-list">
            <li v-for="item in tableStringArray" :key="item">
              <pre>{{ item }}</pre>
            </li>
          </ul>
        </div>
      </div>
      <div class="login-form-c">
        <div class="title">
          <span>{{$t("登录")}}</span>
        </div>
        <div class="auth-code-img-c">
          <div class="title">
            <span>{{$t("请使用微信扫码登录")}}</span>
          </div>
          <img v-if="!isErrorGet" draggable="false" class="auth-code-img" :src="qrUrl">
          <div ref="wechatQRCodeContainer"></div>
          <div v-if="isErrorGet" class="error-get">
            <div>{{$t("二维码获取失败")}}</div>
            <div>{{$t("刷新以重新获取")}}</div>
            <div @click="getQrCode" class="refresh"></div>
          </div>
        </div>
        <div class="auth-code-img-c" style="margin-top: 10px">
          <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" class="demo-ruleForm">
            <el-form-item :label="$t('用户名')" prop="nickName">
              <el-input type="input" v-model="ruleForm.nickName" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item :label="$t('密码')" prop="pass">
              <el-input type="password" v-model="ruleForm.pass" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item :label="$t('验证码')" prop="code">
              <el-input v-model="ruleForm.code" style="position: relative; background: #ddd"></el-input>
              <div class="vercode-mask" style="margin-top: 10px;">
                <img v-show="imgShow" :src="vercodeImgSrc" @click="refVercode()" />
                <div class="vercode-mask" v-show="isOverdue" @click="refVercode()">{{$t('已过期_请刷新')}}</div>
              </div>
            </el-form-item>
            <el-form-item class="button-group">
              <el-button type="primary" @click="submitForm('ruleForm')">{{$t('登录')}}</el-button>
              <el-button @click="register()">{{$t('注册')}}</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { v4 as uuidv4 } from 'uuid';
import storage from "store";
import appConfig from "@/config/appConfig";
import apiService from '@/api/apiService';
import Vue from "vue";
import { getCurrentUser } from "@/utils";

export default {
  name: "QrsceneLogin",
  data() {
    var checkAge = (rule, value, callback) => {
      if (!value) {
        return callback(new Error(this.$t('验证码不能为空')));
      } else {
        callback();
      }
    };
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error(this.$t('请输入用户名')));
      } else if (value.length > 12) {
        callback(new Error(this.$t('用户名长度不能超过12')));
      } else {
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error(this.$t('请输入密码')));
      } else {
        callback();
      }
    };
    return {
      vercodeImgSrc: '', // 验证码图片
      vercodeToken: '', // 验证码验证token
      isOverdue: false,
      imgShow: false,
      qrUrl: '',
      key: '',
      scene_str: '',
      qrCodeDataURL: '',
      tem_poll: '',
      isErrorGet: false,
      services: [], // 存储服务上下架列表
      ruleForm: {
        nickName: '',
        pass: '',
        code: ''
      },
      tableStringArray: [],
      rules: {
        nickName: [
          { validator: validatePass, trigger: 'blur' }
        ],
        pass: [
          { validator: validatePass2, trigger: 'blur' }
        ],
        code: [
          { validator: checkAge, trigger: 'blur' }
        ]
      }
    };
  },
  mounted() {
    this.refVercode();
    this.$nextTick(() => {
      this.generateLoginImg();
      this.tem_poll = setInterval(this.loginPoll, 2000);
      this.fetchServices(); // 获取服务列表
    });
  },
  destroyed() {
    clearInterval(this.tem_poll);
  },
  methods: {
    formatCreateTime(createTime) {
      // 将字符串转换为Date对象
      const date = new Date(createTime);

      // 使用toISOString()方法将Date对象转换为ISO字符串，然后分割
      const [datePart, timePart] = date.toISOString().split('T');

      // 移除时间部分的毫秒，并添加秒
      const formattedTime = timePart.slice(0, 8) + '00';

      // 将日期部分和格式化后的时间部分组合起来
      return `${datePart} ${formattedTime}`;
    },
    generateTableString() {
      this.tableStringArray = this.services.map(service => {
        const formatCreateTime = this.formatCreateTime(service.createTime);
        return `${service.parent}服务${service.serviceName}编号为: ${service.serviceId}在${formatCreateTime}${service.type === 0 ? '上架' : '下架'}`;
      });
      console.log(this.tableStringArray)
    },
    generateLoginImg() {
      this.scene_str = uuidv4();
      // apiService.get('/generatePcQrloginUrl?scene_str=' + this.scene_str).then(res => {
      //   this.qrUrl = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + res.ticket;
      //   this.isImageUrlValid(this.qrUrl).then(() => {
      //     this.isErrorGet = false;
      //   }).catch(() => {
      //     this.isErrorGet = true;
      //   });
      // });
      apiService.get('/pcLoginUrl?scene_str=' + this.scene_str).then(res => {
        this.qrUrl = res.data.imgUrl
        this.key = res.data.key
      });
    },
    fetchServices() {
      apiService.get("/service/log").then((response) => {
        this.services = response.data;
        this.generateTableString();
      }).catch((error) => {
        console.error('Error fetching services:', error);
      });
    },
    isImageUrlValid(url) {
      return new Promise((resolve, reject) => {
        const image = new Image();
        image.onload = () => resolve(true);
        image.onerror = () => reject(new Error('Invalid image URL'));
        image.src = url;
      });
    },
    getQrCode() {
      this.generateLoginImg();
    },
    loginPoll() {
      apiService.post('/pcQrlogin?scene_str=' + this.key).then((res) => {
        if (res.code === 0) {
          clearInterval(this.tem_poll);
          this.$notify({
            title: '登录成功',
            type: 'success',
            duration: 1
          });
          storage.set(appConfig.ACCESS_TOKEN_NAME, res.data, 7 * 24 * 60 * 60 * 1000);
          getCurrentUser();
          apiService.get('/currentUserInfo').then(res => {
            if (res.code === 0) {
              storage.set(appConfig.APP_USER, res.data);
              this.$store.state.id = res.data.id;
              this.$store.state.roleName = res.data.roleName;
              this.$store.state.point = res.data.pointsBalance;
              const path = storage.get(appConfig.LAST_ROUTER);
              if (path) {
                this.$router.push({ path: path });
                storage.remove(appConfig.LAST_ROUTER);
              } else {
                this.$router.push({ name: 'home' });
              }
            } else {
              storage.set(appConfig.ACCESS_TOKEN_NAME, null);
            }
          });
        }
      });
    },
    refVercode() {
      const that = this;
      apiService.get("/code").then(res => {
        that.vercodeImgSrc = res.data.imageBase64Data;
        that.vercodeToken = res.data.vercodeToken;
        this.imgShow = true;
        this.isOverdue = false;
        if (this.timer) clearInterval(this.timer);
        this.timer = setInterval(() => {
          res.data.expireTime--;
          if (res.data.expireTime <= 0) {
            that.isOverdue = true;
            this.imgShow = false;
            clearInterval(this.timer);
          }
        }, 1000);
      });
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let request = {
            nickName: this.ruleForm.nickName,
            pass: this.ruleForm.pass,
            code: this.ruleForm.code,
            codeToken: this.vercodeToken
          };
          apiService.post('/login', request).then(res => {
            if (res.code === 0) {
              storage.set(appConfig.ACCESS_TOKEN_NAME, res.data, 7 * 24 * 60 * 60 * 1000);
              apiService.get('/currentUserInfo').then(res => {
                if (res.code === 0) {
                  storage.set(appConfig.APP_USER, res.data);
                  this.$store.state.id = res.data.id;
                  this.$store.state.roleName = res.data.roleName;
                  this.$store.state.point = res.data.pointsBalance;
                  this.$router.push({ name: 'home' });
                } else {
                  storage.set(appConfig.ACCESS_TOKEN_NAME, null);
                }
              });
            } else {
              Vue.prototype.$message.error(res.msg);
            }
          });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    register() {
      this.$router.push({ path: '/register' });
    }
  },
  computed: {}
};
</script>
<style lang="css" scoped>
.main {
  width: 100vw;
  height: 100vh;
  background: linear-gradient(#c6c6c6, #7af3fd);
  display: flex;
  justify-content: center;
  align-items: center;
}

.container {
  display: flex;
  width: 100%;
  max-width: 1200px;
  height: 100%;
  padding: 20px;
  box-sizing: border-box;
}

.sidebar {
  box-shadow: 0 0 0 .2rem #00000005;
  width: 300px;
  height: 100%;
  background: linear-gradient(#7af3fd, #f6f5f5);
  padding: 20px;
  border-radius: 10px;
  margin-right: 20px;
}

.u4-logo-c {
  text-align: center;
  margin-bottom: 20px;
}
.service-list {
  height: 100%;
  overflow-y: auto;
  background: #e6f7ff; /* 淡蓝色背景 */
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.service-list h3 {
  margin-bottom: 10px;
  font-size: 1.2rem;
  color: #333;
  text-align: center;
  border-bottom: 2px solid #d9ecff;
  padding-bottom: 10px;
}

.notification-list {
  list-style-type: none;
  padding: 0;
  margin: 0;
}

.notification-list li {
  background: #d9ecff; /* 更深的淡蓝色背景 */
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 15px;
  border: 1px solid #b3daff;
  font-size: 0.9rem;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.notification-list pre {
  white-space: pre-wrap;
  word-wrap: break-word;
  margin: 0;
  font-family: monospace;
  color: #333;
}
.u4-logo {
  width: 100px; /* 调整 Logo 大小 */
  height: 100px;
  background: url('@/assets/u4-logo.png') no-repeat center center; /* 确保路径正确 */
  background-size: cover;
}

.service-list {
  height: 100%;
  overflow-y: auto;
}

.service-list h3 {
  margin-bottom: 10px;
  font-size: 1.2rem;
  color: #333;
}

.el-table {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-radius: 4px;
}

.el-table th {
  background-color: #f5f7fa;
  color: #909399;
}

.el-table .el-tag {
  font-size: 0.9rem;
}

.el-table .el-button {
  margin-right: 5px;
}

.login-form-c {
  box-shadow: 0 0 0 .2rem #00000005;
  flex-grow: 1;
  height: 100%;
  background: linear-gradient(#7af3fd, #f6f5f5);
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  border-radius: 10px;
}

.title {
  color: white;
  font-weight: bolder;
  font-size: 25px;
  margin-top: 20px;
  text-align: center;
  width: 100%;
}

.auth-code-img-c {
  margin: 30px auto 0;
  width: 100%;
  max-width: 400px;
  text-align: center;
}

.auth-code-img {
  margin-top: 10px;
  width: 100%;
  user-select: none;
}

.error-get {
  width: 100%;
  height: 100%;
  background-color: rgba(250, 250, 250, 0.5);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.refresh {
  border-radius: 50%;
  background-image: url('@/assets/refresh.svg');
  background-size: contain;
  width: 60px;
  height: 60px;
  margin: 100px auto auto;
}

.refresh:hover {
  cursor: pointer;
  display: inherit;
}

.vercode-mask {
  width: 137px;
  height: 40px;
  background: #000;
  opacity: 0.8;
  text-align: center;
  line-height: 40px;
  color: #fff;
  margin-top: 10px;
}

.button-group {
  margin-top: 10px;
  display: flex;
  justify-content: space-between;
  width: 100%;
}

.button-group .el-button {
  flex: 1;
  min-width: 100px;
  margin: 0 5px;
}

@media (max-width: 768px) {
  .container {
    flex-direction: column;
  }

  .sidebar {
    width: 100%;
    margin-right: 0;
    margin-bottom: 20px;
  }

  .login-form-c {
    width: 100%;
  }

  .auth-code-img-c {
    width: 100%;
  }

  .auth-code-img {
    max-width: 100%;
  }

  .refresh {
    margin: 20px auto auto;
  }

  .el-form-item {
    margin-bottom: 15px;
  }

  .button-group .el-button {
    width: 100%;
    margin: 5px 0;
  }

  .title {
    font-size: 20px;
    margin-top: 10px;
  }

  .service-list h3 {
    font-size: 1.1rem;
  }

  .el-table {
    font-size: 0.9rem;
  }
}
</style>